const db = require('../db/index.js')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const jwtconfig = require('../jwt_config')

exports.register = (req, res) => {
    const reginfo = req.body
    if (!reginfo.account || !reginfo.password) return res.cc('账号或密码不能为空')
    const sql = 'select * from users where account = ?'
    db.query(sql, reginfo.account, (err, result) => {
        if (result.length > 0) return res.cc('账号已存在')
        reginfo.password = bcrypt.hashSync(reginfo.password, 10)
        const sql1 = 'insert into users set ?'
        const identity = '用户'
        const create_time = new Date()
        db.query(sql1, {
            ...reginfo,
            identity,
            create_time,
            status: 0
        }, (err, result) => {
            if (err) return res.cc(err)
            res.send({
                status: 1,
                message: '注册账号成功'
            })
        })
    })
}
exports.login = (req, res) => {
    const logininfo = req.body
    const sql = 'select * from users where account = ?'
    db.query(sql, logininfo.account, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('账号错误')
        const compareResult = bcrypt.compareSync(logininfo.password, result[0].password)
        if (!compareResult) return res.cc('密码错误')
        if (result[0].status == 1) return res.cc('账号被冻结')
        const user = {
            ...result[0],
            password: '',
            imageUrl: '',
            create_time: '',
            update_time: ''
        }
        const tokenStr = jwt.sign(user, jwtconfig.jwtSecretKey, {
            expiresIn: '7h'
        })
        res.send({
            results: result[0],
            status: 0,
            message: '登陆成功',
            token: 'Bearer ' + tokenStr
        })
    })
}